package com.my.main.controller.userAndRight;

import com.github.pagehelper.StringUtil;
import com.my.main.base.controller.BaseController;
import com.my.main.base.entity.Result;
import com.my.main.base.entity.ResultCode;
import com.my.main.common.utils.CurrencyUtil;
import com.my.main.common.utils.JSONUtil;
import com.my.main.entity.userAndRight.SysDepartment;
import com.my.main.entity.userAndRight.SysRightsRoleUserRelation;
import com.my.main.entity.userAndRight.SysUser;
import com.my.main.service.userAndRight.SysDepartmentService;
import com.my.main.service.userAndRight.SysUserService;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.crypto.hash.Sha384Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;


/**
 * 用户管理
 *
 * @author wuh 2020-05-06
 */
@CrossOrigin
@RestController
@RequestMapping(value="/api/v1/sys/user")
public class UserController extends BaseController {


    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysDepartmentService sysDepartmentService;


    /**
     * 条件查询用户列表
     * @param map
     * @return
     */
    @ApiOperation(value="用户与权限 - 查询用户列表")
    @RequestMapping(value="/queryUserList", method = RequestMethod.POST)
    public Result queryUserList(@RequestBody Map<String, Object> map) {
        Map<String, Object> resMap = new HashMap<>();
        resMap.put("page", map.get("page"));
        resMap.put("limit", map.get("limit"));

        try {
            List<Map<String, Object>> resList = new ArrayList<>();
            map.put("page", CurrencyUtil.PageRowNum(Integer.parseInt(map.get("page").toString()), Integer.parseInt(map.get("limit").toString())));

            resMap.put("totalCount", sysUserService.queryCount(map));
            List<SysUser> userList = sysUserService.queryList(map);

            for(SysUser user_t : userList) {
                Map<String, Object> map_t = new HashMap<String, Object>();
                map_t.put("userId", user_t.getUserId());
                SysDepartment sysDep = sysDepartmentService.queryByUuid(user_t.getDepartmentId());
                if (sysDep != null) {
                    map_t.put("depName", sysDep.getName());
                } else {
                    map_t.put("depName", "");
                }
                map_t.put("email", user_t.getEmail());
                map_t.put("phone", user_t.getPhone());
                map_t.put("userName", user_t.getUserName());
                map_t.put("realName", user_t.getRealName());
                map_t.put("head", user_t.getHead());
                map_t.put("status", user_t.getStatus());
                map_t.put("lastEditTime", user_t.getLastEditTime());
                resList.add(map_t);
            }
            resMap.put("userList", resList);
            return new Result(ResultCode.SUCCESS, resMap);
        } catch (Exception e) {
            return new Result(ResultCode.SERVER_ERROR);
        }
    }

    /**
     * 条件查询用户列表
     * @param map
     * @return
     */
    @ApiOperation(value="用户与权限 - 发起合同查询用户列表")
    @RequestMapping(value="/queryUserListForInitiate", method = RequestMethod.POST)
    public Result queryUserListForInitiate(@RequestBody Map<String, Object> map) {
        Map<String, Object> resMap = new HashMap<>();
        resMap.put("page", map.get("page"));
        resMap.put("limit", map.get("limit"));

        try {
            List<Map<String, Object>> resList = new ArrayList<>();
            map.put("page", CurrencyUtil.PageRowNum(Integer.parseInt(map.get("page").toString()), Integer.parseInt(map.get("limit").toString())));

            List<SysUser> userList = sysUserService.queryList(map);

            for(SysUser user_t : userList) {
                Map<String, Object> map_t = new HashMap<String, Object>();
                map_t.put("userId", user_t.getUserId());
                SysDepartment sysDep = sysDepartmentService.queryByUuid(user_t.getDepartmentId());
                if (sysDep != null) {
                    map_t.put("depName", sysDep.getName());
                } else {
                    map_t.put("depName", "");
                }
                map_t.put("email", user_t.getEmail());
                map_t.put("phone", user_t.getPhone());
                map_t.put("userName", user_t.getUserName());
                map_t.put("realName", user_t.getRealName());
                map_t.put("head", user_t.getHead());
                map_t.put("status", user_t.getStatus());
                map_t.put("lastEditTime", user_t.getLastEditTime());
                resList.add(map_t);
            }
            resMap.put("userList", resList);
            return new Result(ResultCode.SUCCESS, resMap);
        } catch (Exception e) {
            return new Result(ResultCode.SERVER_ERROR);
        }
    }


    /**
     * 通过用户ID查询用户信息
     * @param map
     * @return
     */
    @ApiOperation(value="用户与权限 - 查询用户信息")
    @RequestMapping(value="/queryUser", method = RequestMethod.POST)
    public Result queryUser(@RequestBody Map<String, Object> map) {
        Map<String, Object> resMap = new HashMap<>();
        if (map.get("userId") == null || "".equals(map.get("userId").toString())) {
            return new Result(ResultCode.FAIL);
        }

        try {
            SysUser user = sysUserService.queryStringId(map.get("userId").toString());
            resMap.put("userId", user.getUserId());
            List<String> depId = sysDepartmentService.queryDepartmentId(user.getDepartmentId());
            resMap.put("depId", depId);
            resMap.put("email", user.getEmail());
            resMap.put("phone", user.getPhone());
            resMap.put("userName", user.getUserName());
            resMap.put("realName", user.getRealName());
            resMap.put("head", user.getHead());
            resMap.put("status", user.getStatus().equals("locked") ? true : false);

            return new Result(ResultCode.SUCCESS, resMap);
        } catch (Exception e) {
            return new Result(ResultCode.SERVER_ERROR);
        }
    }


    /**
     * 查询当前登录用户信息
     *
     * @author yudongbo 2020-05-23
     */
    @ApiOperation(value="用户与权限 - 查询当前登录用户信息", tags = NOINTERCEPT)
    @RequestMapping(value="/queryCurrentUserInfo", method = RequestMethod.POST)
    public Result queryCurrentUserInfo() {
        Map<String, Object> resMap = new HashMap<>();

        try {
            SysUser user = sysUserService.queryStringId(userInfo.getUserId());
            resMap.put("userId", user.getUserId());
            List<String> depId = sysDepartmentService.queryDepartmentId(user.getDepartmentId());
            resMap.put("depId", depId);
            resMap.put("email", user.getEmail());
            resMap.put("phone", user.getPhone());
            resMap.put("userName", user.getUserName());
            resMap.put("realName", user.getRealName());
            resMap.put("head", user.getHead());
            resMap.put("status", user.getStatus().equals("locked") ? true : false);
            resMap.put("isOringinUser", true);
            return new Result(ResultCode.SUCCESS, resMap);

        } catch (Exception e) {

            logger.error(e);
            return new Result(ResultCode.SERVER_ERROR);

        }
    }


    /**
     * 通过用户ID查询角色ID信息
     * @param map
     * @return
     */
    @ApiOperation(value="用户与权限 - 通过用户ID查询角色ID信息")
    @RequestMapping(value="/queryUserRole", method = RequestMethod.POST)
    public Result queryUserRole(@RequestBody Map<String, Object> map) {
        Map<String, Object> resMap = new HashMap<>();
        if (map.get("userId") == null || "".equals(map.get("userId").toString())) {
            return new Result(ResultCode.FAIL);
        }

        try {
            List<SysRightsRoleUserRelation> userRoleList = sysUserService.queryUserRole(map.get("userId").toString());
            List<String> roleList = new ArrayList<String>();
            for(SysRightsRoleUserRelation userRole_t : userRoleList) {
                roleList.add(userRole_t.getRoleId());
            }
            resMap.put("roleList", roleList);

            return new Result(ResultCode.SUCCESS, resMap);
        } catch (Exception e) {
            return new Result(ResultCode.SERVER_ERROR);
        }
    }


    /**
     * 创建用户
     * @param map
     * @return
     */
    @ApiOperation(value="用户与权限 - 创建用户")
    @RequestMapping(value="/saveUser", method = RequestMethod.POST)
    public Result saveUser(@RequestBody Map<String, Object> map) {
        Map<String, Object> resMap = new HashMap<>();

        Map<String, Object> map_v = testParamMap(map);
        if (!(Boolean) map_v.get("state")) {
            return (Result)map_v.get("result");
        }
        if (StringUtil.isEmpty(map.get("passWord").toString())) {
            return new Result(ResultCode.FAIL, "请填写密码");
        }

        try {
            SysUser user = new SysUser();
            String userId = idWorker.nextId() + "";
            user.setUserId(userId);
            user = assignment(user, map);
            user.setPassWord(new Sha384Hash(map.get("passWord").toString()).toBase64());
            user.setAddIp(requestUtil.getIp());
            user.setAddUserId(userInfo.getUserId());
            user.setLastEditIp(requestUtil.getIp());
            user.setLastEditBy(userInfo.getUserId());
            user.setIsDel(false);

            sysUserService.isSave(user);
            resMap.put("userId", userId);
            return new Result(ResultCode.SUCCESS, resMap);
        } catch (Exception e) {
            return new Result(ResultCode.SERVER_ERROR);
        }
    }


    /**
     * 修改用户
     * @param map
     * @return
     */
    @ApiOperation(value = "用户与权限 - 修改用户")
    @RequestMapping(value="/updateUser", method = RequestMethod.POST)
    public Result updateUser(@RequestBody Map<String, Object> map) {
        Map<String, Object> map_v = testParamMap(map);
        if (!(Boolean) map_v.get("state")) {
            return (Result)map_v.get("result");
        }
        if (StringUtil.isEmpty(map.get("userId").toString())) {
            return new Result(ResultCode.FAIL, "请选择用户");
        }
        if ("1".equals(map.get("userId").toString()) && !"normal".equals(map.get("status").toString())) {
            return new Result(ResultCode.FAIL, "超级管理员无法锁定");
        }

        try {
            SysUser user = sysUserService.queryStringId(map.get("userId").toString());
            user = assignment(user, map);
            if (map.get("passWord") != null && !"".equals(map.get("passWord"))) {
                user.setPassWord(new Sha384Hash(map.get("passWord").toString()).toBase64());
            }
            user.setLastEditIp(requestUtil.getIp());
            user.setLastEditBy(userInfo.getUserId());

            sysUserService.isUpdate(user);
            return new Result(ResultCode.SUCCESS);
        } catch (Exception e) {
            return new Result(ResultCode.SERVER_ERROR);
        }
    }

    /**
     * 修改当前用户
     * @param map
     * @return
     */
    @ApiOperation(value = "用户与权限 - 修改当前用户个人信息(NAVBAR)", tags = NOINTERCEPT)
    @RequestMapping(value="/updateCurrentUser", method = RequestMethod.POST)
    public Result updateCurrentUser(@RequestBody Map<String, Object> map) {
        Map<String, Object> map_v = testParamMap(map);
        if (!(Boolean) map_v.get("state")) {
            return (Result)map_v.get("result");
        }
        if ("1".equals(userInfo.getUserId()) && !"normal".equals(map.get("status").toString())) {
            return new Result(ResultCode.FAIL, "超级管理员无法锁定");
        }

        try {
            SysUser user = sysUserService.queryStringId(userInfo.getUserId());
            user = assignment(user, map);
            if (map.get("passWord") != null && !"".equals(map.get("passWord"))) {
                user.setPassWord(new Sha384Hash(map.get("passWord").toString()).toBase64());
            }
            user.setLastEditIp(requestUtil.getIp());
            user.setLastEditBy(userInfo.getUserId());

            sysUserService.isUpdate(user);
            return new Result(ResultCode.SUCCESS);
        } catch (Exception e) {
            return new Result(ResultCode.SERVER_ERROR);
        }
    }

    /**
     * 锁定与解锁用户
     * @param map
     * @return
     */
    @ApiOperation(value="用户与权限 - 锁定与解锁用户")
    @RequestMapping(value="/lockUser", method = RequestMethod.POST)
    public Result lockUser(@RequestBody Map<String, Object> map) {
        if (StringUtil.isEmpty(map.get("userId").toString())) {
            return new Result(ResultCode.FAIL, "请选择用户");
        }
        if ("1".equals(map.get("userId").toString())) {
            return new Result(ResultCode.FAIL, "超级管理员无法锁定");
        }
        if (StringUtil.isEmpty(map.get("status").toString())) {
            return new Result(ResultCode.FAIL,  "请选择锁定状态");
        } else if (!"locked".equals(map.get("status")) && !"normal".equals(map.get("status"))) {
            return new Result(ResultCode.FAIL,  "锁定类型错误");
        }

        try {
            SysUser user = sysUserService.queryStringId(map.get("userId").toString());
            user.setStatus(map.get("status").toString());
            user.setLastEditIp(requestUtil.getIp());
            user.setLastEditBy(userInfo.getUserId());

            sysUserService.isUpdate(user);
            return new Result(ResultCode.SUCCESS);
        } catch (Exception e) {
            return new Result(ResultCode.SERVER_ERROR);
        }
    }


    /**
     * 添加用户角色
     * @param map
     * @return
     */
    @ApiOperation(value="用户与权限 - 添加用户角色")
    @RequestMapping(value="/saveUserRole", method = RequestMethod.POST)
    public Result saveUserRole(@RequestBody Map<String, Object> map) {
        if (StringUtil.isEmpty(map.get("userId").toString())) {
            return new Result(ResultCode.FAIL, "请选择用户");
        }

        try {
            SysUser user = sysUserService.queryStringId(map.get("userId").toString());
            if (user == null) {
                return new Result(ResultCode.FAIL, "请选择用户");
            }
            List<String> roleIds = null;
            if (!StringUtil.isEmpty(map.get("roleIds").toString())) {
                roleIds = (List<String>)JSONUtil.parseList(map.get("roleIds").toString(), String.class);
                if (roleIds.size() <= 0) {
                    roleIds = null;
                }
            }

            sysUserService.isSvaeUserRole(user.getUserId(), roleIds, userInfo.getUserId(), requestUtil.getIp());
            return new Result(ResultCode.SUCCESS);
        } catch (Exception e) {
            return new Result(ResultCode.SERVER_ERROR);
        }
    }


    /**
     * 根据角色查询用户
     * @param map
     * @return
     */
    @ApiOperation(value="用户与权限 - 根据角色查询用户")
    @RequestMapping(value="/queryUserByRole", method = RequestMethod.POST)
    public Result queryUserByRoleId(@RequestBody Map<String, Object> map) {
        Map<String, Object> resMap = new HashMap<>();
        if (StringUtil.isEmpty(map.get("roleId").toString())) {
            return new Result(ResultCode.FAIL, "请选择角色");
        }

        try {
            resMap.put("userList", sysUserService.queryUserByRoleId(map.get("roleId").toString()));
            return new Result(ResultCode.SUCCESS, resMap);
        } catch (Exception e) {
            return new Result(ResultCode.SERVER_ERROR);
        }
    }


    /**
     * 检验传入的参数
     * @param map
     * @return  true  : 参数全部有效
     *          false : 参数错误
     */
    private Map<String, Object> testParamMap(Map<String, Object> map) {
        Map<String, Object> map_t = new HashMap<String, Object>();
        Boolean state = true;
        Result result = null;
        if (StringUtil.isEmpty(map.get("depId").toString())) {
            state = false;
            result = new Result(ResultCode.FAIL, "请选择部门");
        } else if (StringUtil.isEmpty(map.get("email").toString())) {
            state = false;
            result = new Result(ResultCode.FAIL, "请填写邮箱");
        } else if (StringUtil.isEmpty(map.get("phone").toString())) {
            state = false;
            result = new Result(ResultCode.FAIL, "请填写电话");
        } else if (StringUtil.isEmpty(map.get("userName").toString())) {
            state = false;
            result = new Result(ResultCode.FAIL, "请填写用户名");
        } else if (StringUtil.isEmpty(map.get("realName").toString())) {
            state = false;
            result = new Result(ResultCode.FAIL, "请填写真实姓名");
        } else if (StringUtil.isEmpty(map.get("status").toString())) {
            state = false;
            result = new Result(ResultCode.FAIL, "请选择锁定状态");
        } else if (!"locked".equals(map.get("status").toString()) && !"normal".equals(map.get("status").toString())) {
            state = false;
            result = new Result(ResultCode.FAIL, "请选择锁定状态");
        }
        map_t.put("state", state);
        if (result != null) {
            map_t.put("result", result);
        }
        return map_t;
    }


    /**
     * 对象赋值
     * @param user
     * @param map
     * @return
     */
    private SysUser assignment(SysUser user, Map<String, Object> map) {
        user.setDepartmentId(map.get("depId").toString());
        user.setEmail(map.get("email").toString());
        user.setPhone(map.get("phone").toString());
        user.setUserName(map.get("userName").toString());
        user.setRealName(map.get("realName").toString());
        user.setHead(map.get("head").toString());
        user.setStatus(map.get("status").toString());
        return user;
    }

}
